package de.eridea.learning.java.usermanagement.logic.pwdverification;

import java.util.Hashtable;
import java.util.Set;

public class VerificationProvider {
	private Hashtable<String, PasswordHashFunction> legacyHashFunctions = new Hashtable<String, PasswordHashFunction>();
	private PasswordHashFunction hashFunction;

	public PasswordDigest digest(Password input) {
		return hashFunction.digest(input);
	}

	public boolean verify(Password password, PasswordDigest digest)
			throws UnknownHashFunctionIdException {
		PasswordHashFunction hashFunction = this.hashFunction;
		if (!digest.hashFunctionId.equals(hashFunction.getIdentifier())) {
			hashFunction = legacyHashFunctions.get(digest.hashFunctionId);
			if (hashFunction == null) {
				throw new UnknownHashFunctionIdException(digest.hashFunctionId);
			}
		}
		return digest.equals(hashFunction.digest(password));
	}

	public void setLegacyHashFunctions(Set<PasswordHashFunction> hashFunctions) {
		this.legacyHashFunctions.clear();
		for (PasswordHashFunction item : hashFunctions) {
			this.addLegacyHashFunction(item);
		}
	}

	public void addLegacyHashFunction(PasswordHashFunction hashFunction) {
		this.legacyHashFunctions
				.put(hashFunction.getIdentifier(), hashFunction);
	}

	public void setPasswordHashFunction(PasswordHashFunction hashFunction) {
		this.hashFunction = hashFunction;
	}
}
